package org.chen.wordwave.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.act.BookListAct;
import org.chen.wordwave.act.Review;
import org.chen.wordwave.act.Statistic;
import org.chen.wordwave.act.Translator;
import org.chen.wordwave.act.VideoPlay;
import org.chen.wordwave.act.game.FootballWordGame;
import org.chen.wordwave.act.game.Game;
import org.chen.wordwave.act.game.Lucky;
import org.chen.wordwave.bean.ApiResponse;
import org.chen.wordwave.bean.BookList;
import org.chen.wordwave.bean.Lesson;
import org.chen.wordwave.bean.Reservation;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.image.GlideImageLoader;
import org.chen.wordwave.tools.user.UserUtils;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SouYeFragment extends Fragment {
    private static Map<String, Boolean> reservationStatusMap = new HashMap<>();
    private List<Lesson> lessonList = new ArrayList<>();
    private RecyclerView rv_kc;
    private MyKcAdapter adapter;
    private Context context;
    private Banner banner;
    private List<Integer> images;
    private LinearLayout review, total, lexicography, translate;
    private List<Class<?>> gameActivities;
    private UserInfo currentUser;
    private ApiService apiService;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_souye, container, false);
        context = getActivity();
        rv_kc = view.findViewById(R.id.rv_kc);
        apiService = ApiClient.getClient(context).create(ApiService.class);

        setupLessonList();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        rv_kc.setLayoutManager(linearLayoutManager);
        rv_kc.setNestedScrollingEnabled(false);
        adapter = new MyKcAdapter();
        rv_kc.setAdapter(adapter);

        // 初始化banner - 保持原有代码
        initBanner(view);

        setupButtonListeners(view);

        return view;
    }

    private void initBanner(View view) {
        banner = view.findViewById(R.id.banner);
        images = new ArrayList<>();
        images.add(R.drawable.bg1);
        images.add(R.drawable.bg2);
        images.add(R.drawable.bg3);

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(images);
        banner.setBannerAnimation(Transformer.DepthPage);
        banner.isAutoPlay(true);
        banner.setDelayTime(1500);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.start();

        currentUser = UserUtils.getCurrentUser(getContext());
        gameActivities = new ArrayList<>();
        gameActivities.add(Lucky.class);
        gameActivities.add(Game.class);
        gameActivities.add(FootballWordGame.class);

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (currentUser != null && currentUser.isMember() && currentUser.getMembershipExpiryDate() != null){
                    Intent intent = new Intent(context, gameActivities.get(position));
                    startActivity(intent);
                }else {
                    Toaster.show(getString(R.string.please_become_a_member_first));
                }
            }
        });
    }

    private void setupButtonListeners(View view) {
        review = view.findViewById(R.id.review);
        total = view.findViewById(R.id.total);
        lexicography = view.findViewById(R.id.lexicography);
        translate = view.findViewById(R.id.translate);

        review.setOnClickListener(v -> startActivity(new Intent(getContext(), Review.class)));
        total.setOnClickListener(v -> startActivity(new Intent(getContext(), Statistic.class)));
        lexicography.setOnClickListener(v -> startActivity(new Intent(getContext(), BookListAct.class)));
        translate.setOnClickListener(v -> startActivity(new Intent(getActivity(), Translator.class)));
    }

    // 其他原有方法保持不变...
    private void setupLessonList() {
        loadLessonsFromApi();
    }

    private void loadLessonsFromApi() {
        apiService.getLessonList(1, 50, null).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ApiResponse<Map<String, Object>>> call,
                                   Response<ApiResponse<Map<String, Object>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Map<String, Object>> apiResponse = response.body();
                    if (apiResponse.isSuccess()) {
                        Map<String, Object> data = apiResponse.getData();
                        @SuppressWarnings("unchecked")
                        List<Map<String, Object>> records = (List<Map<String, Object>>) data.get("records");

                        lessonList.clear();
                        for (Map<String, Object> record : records) {
                            Lesson lesson = new Lesson();
                            lesson.setId(((Double) record.get("id")).longValue());
                            lesson.setTitle((String) record.get("title"));
                            lesson.setDescription((String) record.get("description"));
                            lesson.setDuration((String) record.get("duration"));
                            lesson.setVideoUrl((String) record.get("videoUrl"));
                            lesson.setCoverImage((String) record.get("coverImage"));
                            lesson.setLessonNumber(((Double) record.get("lessonNumber")).intValue());
                            lesson.setCategory((String) record.get("category"));
                            if (record.get("viewCount") != null) {
                                lesson.setViewCount(((Double) record.get("viewCount")).intValue());
                            }
                            lessonList.add(lesson);
                        }

                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> adapter.notifyDataSetChanged());
                        }
                    } else {
                        showError("获取课程列表失败: " + apiResponse.getMsg());
                    }
                } else {
                    showError("网络请求失败");
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Map<String, Object>>> call, Throwable t) {
                showError("网络错误: " + t.getMessage());
                setupDefaultLessonList();
            }
        });
    }

    // 更新适配器类
    class MyKcAdapter extends RecyclerView.Adapter<MyKcAdapter.MyViewHolder> {

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_lesson, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            Lesson lesson = lessonList.get(position);
            holder.bindLesson(lesson);
            checkReservationStatus(holder);
        }

        @Override
        public int getItemCount() {
            return lessonList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            private TextView tv_lesson_title, tv_lesson_start, tv_lesson_times;
            private TextView tv_lesson_category, tv_duration_overlay, tv_view_count;
            private RelativeLayout rl_lesson_video;
            private ImageView iv_lesson_background, iv_play_icon;
            private Button btn_reserve_lesson;
            public Lesson currentLesson;

            public MyViewHolder(View itemView) {
                super(itemView);
                initViews(itemView);
                setupClickListeners();
            }

            private void initViews(View itemView) {
                tv_lesson_title = itemView.findViewById(R.id.tv_lesson_title);
                tv_lesson_start = itemView.findViewById(R.id.tv_lesson_start);
                tv_lesson_times = itemView.findViewById(R.id.tv_lesson_times);
                tv_lesson_category = itemView.findViewById(R.id.tv_lesson_category);
                tv_duration_overlay = itemView.findViewById(R.id.tv_duration_overlay);
                tv_view_count = itemView.findViewById(R.id.tv_view_count);
                rl_lesson_video = itemView.findViewById(R.id.rl_lesson_video);
                iv_lesson_background = itemView.findViewById(R.id.iv_lesson_background);
                iv_play_icon = itemView.findViewById(R.id.iv_play_icon);
                btn_reserve_lesson = itemView.findViewById(R.id.btn_reserve_lesson);
            }

            private void setupClickListeners() {
                rl_lesson_video.setOnClickListener(v -> {
                    Intent intent = new Intent(context, VideoPlay.class);
                    if (currentLesson != null) {
                        intent.putExtra("lesson_id", currentLesson.getId());
                        intent.putExtra("lesson_title", currentLesson.getTitle());
                        intent.putExtra("video_url", currentLesson.getVideoUrl());
                        intent.putExtra("cover_image", currentLesson.getCoverImage());
                    }
                    startActivity(intent);
                });

                btn_reserve_lesson.setOnClickListener(v -> handleReservation());
            }

            public void bindLesson(Lesson lesson) {
                currentLesson = lesson;

                // 设置基本信息
                tv_lesson_title.setText(lesson.getTitle());
                tv_lesson_start.setText(lesson.getDescription());
                tv_lesson_times.setText(lesson.getDuration());

                // 加载在线背景图片
                loadBackgroundImage(lesson);

                // 设置分类标签
                setCategoryTag(lesson.getCategory());

                // 设置时长标签
                setDurationTag(lesson.getDuration());

                // 设置观看次数
                setViewCount(lesson.getViewCount());
            }

            private void loadBackgroundImage(Lesson lesson) {
                String imageUrl = lesson.getCoverImage();

                if (imageUrl != null && !imageUrl.isEmpty()) {
                    // 使用Glide加载在线图片
                    RequestOptions options = new RequestOptions()
                            .centerCrop()
                            .placeholder(R.drawable.lesson_bg) // 占位图
                            .error(R.drawable.lesson_bg)       // 错误时的默认图
                            .transform(new RoundedCorners(8)); // 圆角

                    Glide.with(context)
                            .load(imageUrl)
                            .apply(options)
                            .into(iv_lesson_background);
                } else {
                    // 没有在线图片时使用默认图片
                    iv_lesson_background.setImageResource(R.drawable.lesson_bg);
                }
            }

            private void setCategoryTag(String category) {
                if (category != null && !category.isEmpty()) {
                    tv_lesson_category.setVisibility(View.VISIBLE);

                    String categoryText;
                    int backgroundColor;

                    switch (category.toUpperCase()) {
                        case "BASIC":
                            categoryText = "基础";
                            backgroundColor = Color.parseColor("#4CAF50");
                            break;
                        case "INTERMEDIATE":
                            categoryText = "中级";
                            backgroundColor = Color.parseColor("#FF9800");
                            break;
                        case "ADVANCED":
                            categoryText = "高级";
                            backgroundColor = Color.parseColor("#F44336");
                            break;
                        case "BUSINESS":
                            categoryText = "商务";
                            backgroundColor = Color.parseColor("#9C27B0");
                            break;
                        default:
                            categoryText = category;
                            backgroundColor = Color.parseColor("#607D8B");
                            break;
                    }

                    tv_lesson_category.setText(categoryText);
                    tv_lesson_category.setBackgroundColor(backgroundColor);
                } else {
                    tv_lesson_category.setVisibility(View.GONE);
                }
            }

            private void setDurationTag(String duration) {
                if (duration != null && !duration.isEmpty()) {
                    tv_duration_overlay.setVisibility(View.VISIBLE);
                    tv_duration_overlay.setText(duration);
                } else {
                    tv_duration_overlay.setVisibility(View.GONE);
                }
            }

            private void setViewCount(Integer viewCount) {
                if (viewCount != null && viewCount > 0) {
                    tv_view_count.setVisibility(View.VISIBLE);
                    tv_view_count.setText(String.format("观看 %d 次", viewCount));
                } else {
                    tv_view_count.setVisibility(View.GONE);
                }
            }

            private void handleReservation() {
                if (WordInit.userInfo.getEmail() == null) {
                    Toaster.show(getString(R.string.need_login));
                } else {
                    // 保存预约信息到数据库
                    Reservation reservation = new Reservation();
                    reservation.setUserEmail(WordInit.userInfo.getEmail());
                    reservation.setLessonTitle(tv_lesson_title.getText().toString());
                    reservation.setLessonStart(tv_lesson_start.getText().toString());
                    reservation.setLessonTimes(tv_lesson_times.getText().toString());
                    reservation.save();

                    // 更新按钮状态
                    btn_reserve_lesson.setText(R.string.appointment_successful);
                    btn_reserve_lesson.setBackgroundColor(Color.GREEN);
                    btn_reserve_lesson.setEnabled(false);

                    ToastParams toastParams = new ToastParams();
                    toastParams.style = new CustomToastStyle(R.layout.success);
                    toastParams.text = getString(R.string.appointment_successful);
                    Toaster.show(toastParams);

                    updateReservationStatus(tv_lesson_title.getText().toString(), true);
                }
            }
        }

        private void checkReservationStatus(MyViewHolder holder) {
            if (WordInit.userInfo.getEmail() != null) {
                List<Reservation> reservations = LitePal.where("userEmail = ? and lessonTitle = ?",
                        WordInit.userInfo.getEmail(),
                        holder.tv_lesson_title.getText().toString()).find(Reservation.class);
                if (!reservations.isEmpty()) {
                    holder.btn_reserve_lesson.setText(R.string.appointment_successful);
                    holder.btn_reserve_lesson.setBackgroundColor(Color.GREEN);
                    holder.btn_reserve_lesson.setEnabled(false);
                } else {
                    holder.btn_reserve_lesson.setText(R.string.reserve_lesson);
                    holder.btn_reserve_lesson.setBackgroundColor(Color.GRAY);
                    holder.btn_reserve_lesson.setEnabled(true);
                }
            }
        }
    }

    // 其他原有方法保持不变...
    private void showError(String message) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> Toaster.show(message));
        }
    }

    private void setupDefaultLessonList() {
        lessonList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            String title = String.format(getString(R.string.lesson_title), i+1);
            String description = String.format(getString(R.string.lesson_description), i+1);
            String duration = String.format(getString(R.string.lesson_duration), i+1);
            lessonList.add(new Lesson(title, description, duration));
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        View bottomBar = requireActivity().findViewById(R.id.botton_bar);
        if (bottomBar != null) {
            bottomBar.setVisibility(View.VISIBLE);
        }
        adapter.notifyDataSetChanged();
        currentUser = UserUtils.getCurrentUser(getContext());
    }

    public static void updateReservationStatus(String lessonTitle, boolean isReserved) {
        reservationStatusMap.put(lessonTitle, isReserved);
    }
}